package tcpandudp;

import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;

//客户端
public class TcpClientDemo01 {
    public static void main(String[] args) {
        Socket socket = null;
        OutputStream os = null;
        try {
            //1.要知道服务器的地址，和端口号
            InetAddress serverIP = InetAddress.getByName("127.0.0.1");
            int port = 9999;
            System.out.println("客户端连接成功");
            //2.创建一个 socket 连接
            socket = new Socket(serverIP, port);
            //3.发送消息 IO 流
            os = socket.getOutputStream();
            os.write("你好，欢迎学习狂神说Java".getBytes());
            System.out.println("已发送");
        } catch (IOException e) {
            e.printStackTrace();
        }
        //保证代码的严谨性
        if (socket != null) {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (os != null) {
            try {
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

